package br.com.guarana.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class FileDownload extends HttpServlet {

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletContext sc = getServletConfig().getServletContext();
        String caminhoArquivo = request.getParameter("caminhoArquivo");

        try {
            //abre o arquivo
            File arquivo = new File(caminhoArquivo);
            FileInputStream in = new FileInputStream(arquivo);
            OutputStream out = response.getOutputStream();

            //Seta informações na janela de download - nome, tamanho e tipo
            response.setHeader("Content-Disposition", "attachment;filename=\"" + arquivo.getName() + "\"");
            response.setContentLength((int) arquivo.length());
            response.setContentType("application/x-download");

            byte[] buf = new byte[(int) arquivo.length()];

            if (buf.length > 0) {
                int count;
                while ((count = in.read(buf)) >= 0) {
                    out.write(buf, 0, count);
                }
            }
            in.close();
            out.flush();
            out.close();

        } catch (IOException ex) {
            System.out.println("Error in downloadFile: " + ex.getMessage());
            ex.printStackTrace();
        }
    }
}

